#include "gus2_config.h"
#if GUS2_ENABLE_RX
#include "mylist.h"
#include "bytearray.h"
#include "gus2_msg_queue_node.h"

void rx_buff_post_bytearray(bytearray_t* ba);
static LIST_HEAD(_msg_queue);

extern void msg_queue_unlock(void);
extern void msg_queue_lock(void);

#if !GUS2_ENABLE_MALLOC_FREE
extern msg_node_t* gus2_create_message_node();
extern void gus2_free_message_node(msg_node_t* node);
#endif

static msg_node_t* create_msg_node(bytearray_t* ba)
{
#if GUS2_ENABLE_MALLOC_FREE
	msg_node_t* msg_node = (msg_node_t*)gusConfig.malloc(sizeof(msg_node_t));
#else
	msg_node_t* msg_node = gus2_create_message_node();
#endif
	if (msg_node != NULL) {
		msg_node->ba = ba;
	}
	return msg_node;
}
static void free_msg_node(msg_node_t* node) {
#if GUS2_ENABLE_MALLOC_FREE
	gusConfig.free(node);
#else
	gus2_free_message_node(node);
#endif 
}
void rx_msg_queue_push(bytearray_t* ba)
{
	msg_node_t* node = create_msg_node(ba);
	if (node == NULL)
	{
		rx_buff_post_bytearray(ba);
		return;
	}
	msg_queue_lock();
	list_add_tail(&(node->node), &_msg_queue);
	msg_queue_unlock();
}

int rx_msg_queue_get(bytearray_t** pba)
{
	msg_node_t* node = NULL;
	if (list_empty(&_msg_queue))
	{
		return 0;
	}
	msg_queue_lock();
	node = (msg_node_t*)list_entry(_msg_queue.next);
	list_del(&(node->node));
	msg_queue_unlock();
	*pba = node->ba;
	free_msg_node(node);
	return 1;
}

void rx_msg_queue_free(bytearray_t** pba)
{
	rx_buff_post_bytearray(*pba);
}
#endif 

